const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
const eulogyColl = db.collection('eulogie_info');

exports.main = async (event, context) => {
  const { action, content, deadOpenId, commenterOpenId, page = 1, pageSize = 10, id } = event;

  if (action === 'add') {
    if (!content || !deadOpenId || !commenterOpenId) {
      return { success: false, message: '参数不完整' };
    }

    await eulogyColl.add({
      data: {
        deadOpenId,
        commenterOpenId,
        content,
        likes: 0,
        createTime: new Date(),
      }
    });

    return { success: true };
  }

  if (action === 'list') {
    if (!deadOpenId) return { success: false, message: '缺少 deadOpenId' };

    const res = await eulogyColl
      .where({ deadOpenId })
      .orderBy('createTime', 'desc')
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get();

    return {
      success: true,
      eulogies: res.data.map(item => ({
        id: item._id,
        content: item.content,
        likes: item.likes,
        commenterOpenId: item.commenterOpenId,
      })),
    };
  }

  if (action === 'update') {
    const { id, updateData } = event;
    if (!id || !updateData) return { success: false, message: '缺少id或updateData' };

    // 这里只支持更新 likes 字段，比如点赞操作
    return await eulogyColl.doc(id).update({
      data: updateData
    });
  }

  if (action === 'delete') {
    if (!id) return { success: false, message: '缺少 id' };
    await eulogyColl.doc(id).remove();
    return { success: true };
  }

  return { success: false, message: '未知操作' };
};
